package controller;

import java.awt.Image;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import model.Game;
import model.Player;
import model.PublicPlayer;

public class GameManager {
	private static GameManager manager;
	private HashMap<String, Player> players;
	private HashMap<Integer, Game> games;
	private HashMap<String, List<Integer>> player_game_list;
	
	private int game_counter;
	
	protected GameManager() {
		players = new HashMap<String, Player>();
		game_counter = 0;
	}
	
	public static GameManager getInstance() {
		if (manager == null) {
			manager = new GameManager();
			return manager;
		}
		else
			return manager;
	}
	
	public void login(String id, Player player) {
		players.put(id, player);
		if (!player_game_list.containsKey(id))
			player_game_list.put(id, new LinkedList<Integer>());
	}
	
	public List<PublicPlayer> getGames(String player_id) {
		List<Integer> game_list = player_game_list.get(player_id);
		List<PublicPlayer> player_list = new LinkedList<PublicPlayer>();
		for (int i = 0; i < game_list.size(); ++i) {
			Game game = games.get(game_list.get(i));
			player_list.add(players.get(game.getFromPlayer()));
		}
		return player_list;
	}
	
	public List<PublicPlayer> getFriends(String player_id) {
		return players.get(player_id).getAllFriends();
	}
	
	public int newGame(String player1, String player2) {
		List<Integer> game_list = player_game_list.get(player1);
		for (int i = 0; i < game_list.size(); ++i) {
			Game game = games.get(game_list.get(i));
			if (game.getFromPlayer().equals(player2)) {
				//continue game
				continueGame(game_list.get(i), game.getImage(), game.getAnswer());
				return 0;
			}
			else if (game.getToPlayer().equals(player2)) {
				//wait
				return 0;
			}
		}
		
		Game game = new Game(player1, player2);
		games.put(game_counter, game);
		player_game_list.get(player1).add(game_counter);
		player_game_list.get(player2).add(game_counter);
		++game_counter;
		return game_counter - 1;
	}
	
	public List<PublicPlayer> getMutualFriend(String player1_id, String player2_id) {
		List<PublicPlayer> mutualFriends = new LinkedList<PublicPlayer>();
		Player player1 = players.get(player1_id);
		Player player2 = players.get(player2_id);
		List<PublicPlayer> friends1 = player1.getAllFriends();
		List<PublicPlayer> friends2 = player2.getAllFriends();
		for (int i = 0; i < friends1.size(); ++i) {
			PublicPlayer player = friends1.get(i);
			if (friends2.contains(player))
				mutualFriends.add(player);
		}
		return mutualFriends;
	}
	
	public void continueGame(int game_id, Image image, String answer) {
		Game game = games.get(game_id);
		game.add(image, answer);
	}
}
